﻿Shader "Custom/TestShader17"
{
    Properties
    {
        _MainTex("Base (RGB)", 2D) = "white" {}
        _EdgeOnly("EdgeOnly", range(0,1)) = 0
        _EdgeColor("EdgeColor", Color) = (0,0,0,0)
        _BackgroundColor("BackgroundColor", Color) = (1,1,1,1)
    }
	SubShader
	{
		Pass
		{
            ZWrite Off
            Cull Off
            ZTest Always

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"

			struct v2f
			{
				float4 pos : SV_POSITION;
				float2 uv[9] : TEXCOORD0;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
            float4 _MainTex_TexelSize;
            float _EdgeOnly;
            float4 _EdgeColor;
            float4 _BackgroundColor;
			
			v2f vert (appdata_img v)
			{
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                float2 uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;

                o.uv[0] = uv + _MainTex_TexelSize.xy * float2(-1, 1);
                o.uv[1] = uv + _MainTex_TexelSize.xy * float2(0, 1);
                o.uv[2] = uv + _MainTex_TexelSize.xy * float2(1, 1);

                o.uv[3] = uv + _MainTex_TexelSize.xy * float2(-1, 0);
                o.uv[4] = uv + _MainTex_TexelSize.xy * float2(0, 0);
                o.uv[5] = uv + _MainTex_TexelSize.xy * float2(1, 0);

                o.uv[6] = uv + _MainTex_TexelSize.xy * float2(-1, -1);
                o.uv[7] = uv + _MainTex_TexelSize.xy * float2(0, -1);
                o.uv[8] = uv + _MainTex_TexelSize.xy * float2(1, -1);
                return o;
			}
			
            fixed luminance(fixed4 color)
            {
                fixed3 gray = fixed3(0.2125, 0.7154, 0.0721);
                return dot(gray, color.rgb);
            }


            fixed sobel(v2f i)
            {
                const fixed Gy[9] = { -1, -2, -1,
                                       0, 0, 0,
                                       1, 2, 1};

                const fixed Gx[9] = { -1, 0, 1,
                                      -2, 0, 2,
                                      -1, 0, 1};
                
                fixed texColor;
                fixed edgeX = 0;
                fixed edgeY = 0;
                for (int it = 0; it < 9; it++)
                {
                    texColor = luminance(tex2D(_MainTex, i.uv[it]));
                    edgeX += texColor * Gx[it];
                    edgeY += texColor * Gy[it];
                }

                return 1 - abs(edgeX) - abs(edgeY);
            }

			fixed4 frag (v2f i) : SV_Target
			{
                fixed edge = sobel(i);
                //纹理颜色 
                fixed4 texColor = tex2D(_MainTex, i.uv[4]);

                fixed3 finalColor = lerp(_EdgeColor, texColor.rgb, edge);
                return fixed4(finalColor, 1); 
			}
			ENDCG
		}
	}
    Fallback Off
}
